package command

import (
	"flag"
	"fmt"
	"gitee.com/huanminabc/go-utils/common"
	"os"
)

type command interface {
	//绑定
	Bind()
	//满足条件
	Condition() bool
	//执行命令
	Execute()
	//获取命令名称
	GetName() string

	//获取命令描述
	GetDesc() string
	//优先级  ,0最低...
	GetPriority() int
	//是否终止
	IsExit() bool
}

var commands = []command{}

// 注册命令
func RegisterCommand(c command) {
	//判断是否已经存在
	for _, v := range commands {
		if v.GetName() == c.GetName() {
			panic("命令已注册过了")
		}
	}
	commands = append(commands, c)
	//按照优先级排序,从大到小
	common.SortSlice[command](&commands, 1, func(i, j command) int {
		return i.GetPriority() - j.GetPriority()
	})
}

// 执行命令
func ExecuteCommand() {

	strings__ := os.Args[1:]
	//检查用户是否输入了脚本,而不是命令
	if len(strings__) == 1 && strings__[0][0] != '-' {
		CheckTime()
		code := strings__[0]
		//执行命令
		cmd := &ScriptCmd{}
		cmd.doc = code
		cmd.Execute()
		return
	}
	//判断是否是-books 如果是那么就在后面补充一个空位,防止后面的命令出错
	if len(strings__) == 1 && strings__[0] == "-books" {
		strings__[0] = "-books=''"
	}

	//绑定参数
	for _, v := range commands {
		v.Bind()
	}
	//解析参数,就是用户输入的命令
	flag.Parse()
	//如果啥也没有那么打印帮助
	if len(os.Args) == 1 {
		fmt.Println("作者: huanmin")
		fmt.Println("版本: 免费版1.0,每天9~17点可用")
		fmt.Println("联系方式:3426154361@qq.com")
		fmt.Println("1.邮箱 3426154361@qq.com")
		fmt.Println("2.微信 hu867682752")
		fmt.Println("相关命令:")
		flag.PrintDefaults()
		return
	}

	//执行满足条件的命令
	for _, v := range commands {
		if v.Condition() {
			v.Execute()
			if v.IsExit() {
				break
			}
		}
	}

}

// 使用期限检查,如果在非9点到17点之间,则退出程序
func CheckTime() {
	////获取当前时间
	//hour, _, _ := time.Now().Clock()
	//var start = "111O111Q==111" //9
	////清除111
	//start = strings.ReplaceAll(start, "111", "")
	//var end = "111M111Tc=111" //17
	////清除111
	//end = strings.ReplaceAll(end, "111", "")
	////解密
	//start = encrypt.Base64StrDecode(start)
	//end = encrypt.Base64StrDecode(end)
	////转换为int
	//startInt, _ := strconv.Atoi(start)
	//endInt, _ := strconv.Atoi(end)
	////判断是否在9点到17点之间
	//if hour < startInt || hour >= endInt {
	//	var message = "5b2T5YmN5pe26Ze05LiN5ZyoOeeCueWIsDE354K55LmL6Ze0LOivt+WcqDnngrnliLAxN+eCueS5i+mXtOS9v+eUqOOAguaIluiAhei0reS5sOS4k+S4mueJiOS9v+eUqO+8jOivt+iBlOezu+S9nOiAhei0qOivouS7t+agvOiwouiwouOAggotIOW+ruS/oTogaHU4Njc2ODI3NTIKLSDmiYvmnLo6IDE3NTU0MjcxNTUx"
	//	fmt.Println(encrypt.Base64StrDecode(message))
	//	os.Exit(1)
	//}
}
